package com.sgb.kjwl.view.ui.activity.self.packers;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;

import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;

import androidx.lifecycle.ViewModelProvider;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;

import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.AtSelfTeamAlbumBinding;

import com.sgb.kjwl.model.entity.packers.TeamAlbumEntity;
import com.sgb.kjwl.model.entity.packers.TeamAlbumPositionEntity;

import com.sgb.kjwl.view.ui.adapter.packers.TeamAlbumAdapter;

import com.sgb.kjwl.viewmodel.self.packers.SelfTeamAlbumModel;



import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.helper.OnMultiClickListener;

import com.swgk.core.util.MToast;

import com.swgk.core.common.base.BaseActivity;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;



/**
 * @author: 王彬臣
 * @date: 2021/9/8
 * @Description: v2.9.5  个人中心-工队相册
 */
public class SelfTeamAlbumActivity extends BaseActivity<SelfTeamAlbumModel, AtSelfTeamAlbumBinding> {
    boolean isEdit = true;
    List<TeamAlbumEntity> mList = new ArrayList<>();
    TeamAlbumAdapter mAdapter;
    int itemPosition;


    private List<File> fileList = new ArrayList<>();

    boolean mIsLoadMore;

    //保存一个新删除数组 防止接口报错存储
    List<TeamAlbumEntity> mSaveList = new ArrayList<>();
    //删除的数组
    Map<Integer,TeamAlbumPositionEntity> delMaps=new HashMap<>();
    private Gson mGson = new Gson();
    @Override
    protected int layoutId() {
        return R.layout.at_self_team_album;
    }

    @Override
    protected void createViewModel() {
        mViewModel = new ViewModelProvider(this).get(SelfTeamAlbumModel.class);

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    public static void start(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, SelfTeamAlbumActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void init() {
        mBinding.setOnClick(this);
        mBinding.actionBar.setOnBackClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mBinding.actionBar.setMenuFunctionClick(new OnMultiClickListener() {
            @Override
            public void onMultiClick(View v) {
                if (isEdit) {
                    isEdit = false;
                    mBinding.actionBar.setMenuFunctionText("取消");
                    mAdapter.setShowEdit(true);
                    mAdapter.notifyDataSetChanged();
                    mBinding.tvDel.setVisibility(View.VISIBLE);
                    mBinding.refreshLayout.setEnableLoadMore(false);
                    mBinding.refreshLayout.setEnableRefresh(false);
                } else {
                    isEdit = true;
                    delMaps.clear();
                    mAdapter.setShowEdit(false);
                    mAdapter.notifyDataSetChanged();
                    mBinding.actionBar.setMenuFunctionText("编辑");
                    mBinding.tvDel.setVisibility(View.GONE);
                    mBinding.refreshLayout.setEnableLoadMore(true);
                    mBinding.refreshLayout.setEnableRefresh(true);
                }

            }
        });

        initRecycler();
        initData();
    }

    private void initRecycler() {
        mBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new TeamAlbumAdapter(mList);
        mBinding.refreshLayout.setEnableRefresh(true);
        mBinding.refreshLayout.setEnableLoadMore(true);
        mBinding.refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mIsLoadMore = true;
                getData();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mIsLoadMore = false;
                getData();
            }
        });
        mAdapter.setOnItemClickListener(new TeamAlbumAdapter.onItemClickListener() {
            @Override
            public void onItemClick(int position) {
                itemPosition = position;
            }

            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void getDel(int mainPosition, Map<Integer, String> delMap) {
                TeamAlbumPositionEntity data=new TeamAlbumPositionEntity();
                if(!delMap.isEmpty()){
                    List<String> delUrl=new ArrayList<>();
                    for(Integer pos:delMap.keySet()){
                        delUrl.add(delMap.get(pos));
                    }
                    data.setDelUrl(delUrl);
                    if(!delMaps.containsKey(mainPosition)) {
                        delMaps.put(mainPosition, data);
                    }else{
                        delMaps.replace(mainPosition,data);
                    }
                }else if(delMap.isEmpty()){
                    delMaps.remove(mainPosition);
                }

            }
        });
        mBinding.recyclerView.setAdapter(mAdapter);
        mAdapter.bindToRecyclerView(mBinding.recyclerView);
        mAdapter.setEmptyView(R.layout.layout_empty);
    }

    private void initData() {
        mViewModel.ldAlbum.observe(this, data -> {
            mBinding.refreshLayout.finishRefresh();
            mBinding.refreshLayout.finishLoadMore();
            if(mViewModel.pageNum==1){
                mList.clear();
            }
            if(data.getList().size()>0) {
                mList.addAll(data.getList());
            }
            mAdapter.notifyDataSetChanged();
            if (data.getCurrentPage() < data.getTotalPage()) {
                mBinding.refreshLayout.resetNoMoreData();
            } else {
                mBinding.refreshLayout.finishLoadMoreWithNoMoreData();
            }

            if (mList.size() == 0) {
                mBinding.actionBar.setMenuFunctionVisible(false);
            }
        });
        mViewModel.uploadUrls.observe(this, urls -> {
            mList.get(itemPosition).getTeamUrlList().addAll(urls);
            mAdapter.notifyDataSetChanged();
            showLoading();
            List<TeamAlbumEntity> mSaveList = new ArrayList<>();
            mSaveList.add(mList.get(itemPosition));
            mViewModel.savePhotoData(this,mSaveList);
        });
        mViewModel.ldDelResult.observe(this,result->{
            if(result){
                for(int i=0;i<mList.size();i++){
                    TeamAlbumEntity albumEntity=mList.get(i);
                    if(albumEntity.getTeamUrlList().size()>0){
                        for(TeamAlbumEntity data:mSaveList){
                            if(data.getTeamNo().equals(albumEntity.getTeamNo())){
                                albumEntity.setTeamUrlList(data.getTeamUrlList());
                            }
                        }
                    }
                }
                mAdapter.notifyDataSetChanged();
                mSaveList.clear();
                delMaps.clear();
            }
        });
        getData();
    }

    private void getData() {
        showLoading();
        mViewModel.requestTeamAlbumData(mIsLoadMore);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {//获取相册返回的图片
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);

                fileList.clear();
                for (LocalMedia localMedia : selectList) {
                    File file = new File(localMedia.getCompressPath());
                    fileList.add(file);
                }
                if (fileList.size() > 0) {
                    showLoading();
                    mViewModel.uploadMutiFileModel(fileList);
                }

            }
        }
    }

   public void showLoading(){
       DialogHelper.showProgressDialog(this, null, "数据加载中...", 0, false,null).setCanceledOnTouchOutside(false);
   }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_del:

                        if (delMaps.isEmpty()) {
                            MToast.showToast(this, "请选择要删除的图片");
                            return;
                        }

                new RoundDialog.Builder(this)
                        .title("温馨提示")
                        .content("确认删除？")
                        .cancel("取消")
                        .confirm("确定")
                        .cancelable(false)
                        .confirmCallback(v12 -> {
                                delPic();
                        }).show();

                break;
        }
    }

    //通过删除的集合遍历找到对应的位置移除
    private void delPic() {
        showLoading();
        mSaveList.clear();
        //设置新列表数组，不获取当前列表数组引用
        String data = mGson.toJson(mList);
        List<TeamAlbumEntity> copyList = mGson.fromJson(data, new TypeToken<List<TeamAlbumEntity>>() {
        }.getType());
        //遍历删除对应位置
        for(int i=0;i<copyList.size();i++){
            TeamAlbumEntity albumEntity=copyList.get(i);
            if(albumEntity.getTeamUrlList().size()>0){
                Iterator<Map.Entry<Integer,TeamAlbumPositionEntity>> entries = delMaps.entrySet().iterator();
                while (entries.hasNext()){
                    Map.Entry<Integer, TeamAlbumPositionEntity> del=entries.next();
                    if(del.getKey()==i){
                        for(int m=0;m<del.getValue().getDelUrl().size();m++) {
                            String delUrl=del.getValue().getDelUrl().get(m);
                            Iterator<String> iterator = albumEntity.getTeamUrlList().iterator();
                            while (iterator.hasNext()) {
                                String url = iterator.next();
                                if (url.equals(delUrl)){
                                    iterator.remove();
                                }
                            }
                        }
                        mSaveList.add(albumEntity);
                    }
                }

            }
        }

        //调保存接口更新数据
        mViewModel.savePhotoData(this,mSaveList,mBinding.tvDel);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();

    }


}
